package cn.lbd;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class CuratorGet {
    private final String SOCKET_ADDRESS = "39.97.191.1:2181";
    CuratorFramework client;

    @Before
    public void init() {
        client = CuratorFrameworkFactory.builder()
                .connectString(SOCKET_ADDRESS)
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("create_new")
                .build();

        client.start();
        System.out.println(client.isStarted());
    }

    @After
    public void destroy() {
        client.close();
    }

    @Test
    public void test1() throws Exception {
        byte[] bytes = client.getData()
                .forPath("/demo1");
        System.out.println(new String(bytes));
    }

    //Stat
    @Test
    public void test2() throws Exception {
        Stat stat = new Stat();
        byte[] bytes = client.getData()
                //读取属性到stat对象
                .storingStatIn(stat)
                .forPath("/demo1");
        System.out.println(new String(bytes));
        System.out.println(stat.getVersion());
    }

    //异步读取
    @Test
    public void test3() throws Exception {
        byte[] bytes = client.getData()
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorEvent.getPath());
                        System.out.println(curatorEvent.getType());
                        System.out.println(new String(curatorEvent.getData()));
                    }
                })
                .forPath("/demo1");
        //异步回调，这里是拿不到数据的
        //System.out.println(new String(bytes));
        TimeUnit.SECONDS.sleep(3);
        System.out.println("结束");
    }

    @Test
    public void test4() {

    }
}
